<!DOCTYPE html><html><head>
<title>critcl_use - C Runtime In Tcl (CriTcl)</title>
<style type="text/css"><!--
    HTML {
	background: 	#FFFFFF;
	color: 		black;
    }
    BODY {
	background: 	#FFFFFF;
	color:	 	black;
    }
    DIV.doctools {
	margin-left:	10%;
	margin-right:	10%;
    }
    DIV.doctools H1,DIV.doctools H2 {
	margin-left:	-5%;
    }
    H1, H2, H3, H4 {
	margin-top: 	1em;
	font-family:	sans-serif;
	font-size:	large;
	color:		#005A9C;
	background: 	transparent;
	text-align:		left;
    }
    H1.doctools_title {
	text-align: center;
    }
    UL,OL {
	margin-right: 0em;
	margin-top: 3pt;
	margin-bottom: 3pt;
    }
    UL LI {
	list-style: disc;
    }
    OL LI {
	list-style: decimal;
    }
    DT {
	padding-top: 	1ex;
    }
    UL.doctools_toc,UL.doctools_toc UL, UL.doctools_toc UL UL {
	font:		normal 12pt/14pt sans-serif;
	list-style:	none;
    }
    LI.doctools_section, LI.doctools_subsection {
	list-style: 	none;
	margin-left: 	0em;
	text-indent:	0em;
	padding: 	0em;
    }
    PRE {
	display: 	block;
	font-family:	monospace;
	white-space:	pre;
	margin:		0%;
	padding-top:	0.5ex;
	padding-bottom:	0.5ex;
	padding-left:	1ex;
	padding-right:	1ex;
	width:		100%;
    }
    PRE.doctools_example {
	color: 		black;
	background: 	#f5dcb3;
	border:		1px solid black;
    }
    UL.doctools_requirements LI, UL.doctools_syntax LI {
	list-style: 	none;
	margin-left: 	0em;
	text-indent:	0em;
	padding:	0em;
    }
    DIV.doctools_synopsis {
	color: 		black;
	background: 	#80ffff;
	border:		1px solid black;
	font-family:	serif;
	margin-top: 	1em;
	margin-bottom: 	1em;
    }
    UL.doctools_syntax {
	margin-top: 	1em;
	border-top:	1px solid black;
    }
    UL.doctools_requirements {
	margin-bottom: 	1em;
	border-bottom:	1px solid black;
    }
--></style>
</head>
<!-- Generated from file 'critcl_usingit.man' by tcllib/doctools with format 'html'
   -->
<!-- Copyright &amp;copy; Jean-Claude Wippler   -- Copyright &amp;copy; Steve Landers   -- Copyright &amp;copy; 2011-2018 Andreas Kupries
   -->
<!-- critcl_use.n
   -->
<body><hr> [
   <a href="../toc.html">Table Of Contents</a>
| <a href="../index.html">Keyword Index</a>
 ] <hr>
<div class="doctools">
<h1 class="doctools_title">critcl_use(n) 3.1.18.1 doc &quot;C Runtime In Tcl (CriTcl)&quot;</h1>
<div id="name" class="doctools_section"><h2><a name="name">Name</a></h2>
<p>critcl_use - Using Critcl</p>
</div>
<div id="toc" class="doctools_section"><h2><a name="toc">Table Of Contents</a></h2>
<ul class="doctools_toc">
<li class="doctools_section"><a href="#toc">Table Of Contents</a></li>
<li class="doctools_section"><a href="#section1">Description</a></li>
<li class="doctools_section"><a href="#section2">Embedding C</a>
<ul>
<li class="doctools_subsection"><a href="#subsection1">A Simple Procedure</a></li>
<li class="doctools_subsection"><a href="#subsection2">Custom Types, Introduction</a></li>
<li class="doctools_subsection"><a href="#subsection3">Custom Types, Semi-trivial</a></li>
<li class="doctools_subsection"><a href="#subsection4">Custom Types, Support structures</a></li>
<li class="doctools_subsection"><a href="#subsection5">Custom Types, Results</a></li>
<li class="doctools_subsection"><a href="#subsection6">Handling A Variable Number Of Arguments</a></li>
<li class="doctools_subsection"><a href="#subsection7">Data As A Tcl Command</a></li>
<li class="doctools_subsection"><a href="#subsection8">Blocks of arbitrary C</a></li>
<li class="doctools_subsection"><a href="#subsection9">Constant values</a></li>
<li class="doctools_subsection"><a href="#subsection10">Lifting constants</a></li>
<li class="doctools_subsection"><a href="#subsection11">Finding header files</a></li>
<li class="doctools_subsection"><a href="#subsection12">Separate C sources</a></li>
<li class="doctools_subsection"><a href="#subsection13">Finding external libraries</a></li>
<li class="doctools_subsection"><a href="#subsection14">Customizing the compile and link steps</a></li>
<li class="doctools_subsection"><a href="#subsection15">Having both C and Tcl functionality</a></li>
<li class="doctools_subsection"><a href="#subsection16">Using C with Tcl functionality as fallback</a></li>
<li class="doctools_subsection"><a href="#subsection17">Unlazy Packages</a></li>
</ul>
</li>
<li class="doctools_section"><a href="#section3">Checking your C</a>
<ul>
<li class="doctools_subsection"><a href="#subsection18">Which Tcl ?</a></li>
<li class="doctools_subsection"><a href="#subsection19">Making A Widget</a></li>
<li class="doctools_subsection"><a href="#subsection20">Checking The Environment</a></li>
<li class="doctools_subsection"><a href="#subsection21">License Invoked</a></li>
</ul>
</li>
<li class="doctools_section"><a href="#section4">Building Critcl Packages</a>
<ul>
<li class="doctools_subsection"><a href="#subsection22">Getting Help ...</a></li>
<li class="doctools_subsection"><a href="#subsection23">Pre-Filling The Result Cache</a></li>
<li class="doctools_subsection"><a href="#subsection24">Building A Package</a></li>
<li class="doctools_subsection"><a href="#subsection25">Building And Installing A Package</a></li>
<li class="doctools_subsection"><a href="#subsection26">Building For Debugging</a></li>
<li class="doctools_subsection"><a href="#subsection27">Retargeting The Binaries</a></li>
<li class="doctools_subsection"><a href="#subsection28">Custom Configurations</a></li>
<li class="doctools_subsection"><a href="#subsection29">Custom Header Path</a></li>
<li class="doctools_subsection"><a href="#subsection30">Introspection of Targets And Configurations</a></li>
</ul>
</li>
<li class="doctools_section"><a href="#section5">Authors</a></li>
<li class="doctools_section"><a href="#section6">Bugs, Ideas, Feedback</a></li>
<li class="doctools_section"><a href="#keywords">Keywords</a></li>
<li class="doctools_section"><a href="#category">Category</a></li>
<li class="doctools_section"><a href="#copyright">Copyright</a></li>
</ul>
</div>
<div id="section1" class="doctools_section"><h2><a name="section1">Description</a></h2>
<p><i class="term">C Runtime In Tcl</i>, or <i class="term"><a href="critcl_pkg.html">CriTcl</a></i> , is a system for compiling C code
embedded in Tcl on the fly and either loading the resulting objects into Tcl for
immediate use or packaging them for distribution.  Use <i class="term"><a href="critcl_pkg.html">CriTcl</a></i> to improve
performance by rewriting in C those routines that are performance bottlenecks.</p>
<p>This document is a (hopefully) gentle introduction to Critcl by way of a
series of small examples.</p>
<p>Readers which came directly to this document through a search
or similar, and are thus in need of an overview of the whole system,
are advised to read the <i class="term"><a href="critcl_introduction.html">Introduction To CriTcl</a></i> first.</p>
<p>The examples here cover both how to embed C into Tcl with it,
and how to build the distributable packages.
As such the intended audience are both writers of packages with
embedded C, and people building such packages.
To make things easier the two themes each have their own section in
this document, enabling all readers to quickly skip the part they are
not interested in.</p>
<p>The sources of Critcl, should you have gotten them, contain
several larger examples show-casing various aspects of the
system. These demonstration packages can all be found in the
sub-directory &quot;<b class="file">examples/</b>&quot; of the sources.</p>
</div>
<div id="section2" class="doctools_section"><h2><a name="section2">Embedding C</a></h2>
<p>This is the section for developers writing, or wishing to write, a
package embedding C into Tcl via critcl.</p>
<p>I guess that we are allowed to asssume that you, gentle reader, are
here because you have written some Tcl code which is not fast enough
(any more) and you wish to make it &quot;go faster&quot; by replacing parts (or
all) of it with speedy C.</p>
<p>Another, and I believe reasonable assumption to make would be that you
have already investigated and ruled out or done things like changes to
data structures and algorithms which reduce O(n*n) work to O (n*log n),
O(n), or even O(1).
Of course, nothing prevents you from forging ahead here even if you
have not done such. Still, even in that case I would recommend that
you consider investigating this line of making your code go faster as
well.</p>
<p>Now, with these introductory words out of the way, lets jump into the
meat of things.</p>
<div id="subsection1" class="doctools_subsection"><h3><a name="subsection1">A Simple Procedure</a></h3>
<p>Starting simple, let us assume that the Tcl code in question is
something like</p>
<pre class="doctools_example">
    proc math {x y z} {
        return [expr {(sin($x)*rand())/$y**log($z)}]
    }
</pre>
<p>with the expression pretending to be something very complex and
slow. Converting this to C we get:</p>
<pre class="doctools_example">
    critcl::cproc math {double x double y double z} double {
        double up   = rand () * sin (x);
        double down = pow(y, log (z));
        return up/down;
    }
</pre>
<p>Notable about this translation:</p>
<ol class="doctools_enumerated">
<li><p>All the arguments got type information added to them, here
       &quot;double&quot;.  Like in C the type precedes the argument name. Other
       than that it is pretty much a Tcl dictionary, with keys and
       values swapped.</p></li>
<li><p>We now also have to declare the type of the result, here
       &quot;double&quot;, again.</p></li>
<li><p>The reference manpage lists all the legal C types supported as
       arguments and results.</p></li>
</ol>
</div>
<div id="subsection2" class="doctools_subsection"><h3><a name="subsection2">Custom Types, Introduction</a></h3>
<p>When writing bindings to external libraries <b class="cmd">critcl::cproc</b> is
usually the most convenient way of writing the lower layers. This is
however hampered by the fact that critcl on its own only supports a
few standard (arguably the most import) standard types, whereas the
functions we wish to bind most certainly will use much more, specific
to the library's function.</p>
<p>The critcl commands <b class="cmd">argtype</b>, <b class="cmd">resulttype</b> and their
adjuncts are provided to help here, by allowing a developer to extend
critcl's type system with custom conversions.</p>
<p>This and the three following sections will demonstrate this,
from trivial to complex.</p>
<p>The most trivial use is to create types which are aliases of
existing types, standard or other. As an alias it simply copies and
uses the conversion code from the referenced types.</p>
<p>Our example is pulled from an incomplete project of mine, a
binding to <i class="term">Jeffrey Kegler</i>'s <i class="term">libmarpa</i> library managing
Earley parsers. Several custom types simply reflect the typedef's done
by the library, to make the <b class="cmd">critcl::cproc</b>s as self-documenting
as the underlying library functions themselves.</p>
<pre class="doctools_example">
    critcl::argtype Marpa_Symbol_ID     = int
    critcl::argtype Marpa_Rule_ID       = int
    critcl::argtype Marpa_Rule_Int      = int
    critcl::argtype Marpa_Rank          = int
    critcl::argtype Marpa_Earleme       = int
    critcl::argtype Marpa_Earley_Set_ID = int
    ...
    method sym-rank: proc {
        Marpa_Symbol_ID sym
        Marpa_Rank      rank
    } Marpa_Rank {
        return marpa_g_symbol_rank_set (instance-&gt;grammar, sym, rank);
    }
    ...
</pre>
</div>
<div id="subsection3" class="doctools_subsection"><h3><a name="subsection3">Custom Types, Semi-trivial</a></h3>
<p>A more involved custom argument type would be to map from Tcl strings
to some internal representation, like an integer code.</p>
<p>The first example is taken from the <b class="package">tclyaml</b> package,
a binding to the <b class="package">libyaml</b> library. In a few places we have to
map readable names for block styles, scalar styles, etc. to the
internal enumeration.</p>
<pre class="doctools_example">
    critcl::argtype yaml_sequence_style_t {
        if (!encode_sequence_style (interp, @@, &amp;@A)) return TCL_ERROR;
    }
    ...
    critcl::ccode {
        static const char* ty_block_style_names [] = {
            &quot;any&quot;, &quot;block&quot;, &quot;flow&quot;, NULL
        };
        static int
        encode_sequence_style (Tcl_Interp* interp, Tcl_Obj* style,
                               yaml_sequence_style_t* estyle)
        {
            int value;
            if (Tcl_GetIndexFromObj (interp, style, ty_block_style_names,
                                     &quot;sequence style&quot;, 0, &amp;value) != TCL_OK) {
                return 0;
            }
            *estyle = value;
            return 1;
        }
    }
    ...
    method sequence_start proc {
        pstring anchor
        pstring tag
        int implicit
        yaml_sequence_style_t style
    } ok {
        /* Syntax: &lt;instance&gt; seq_start &lt;anchor&gt; &lt;tag&gt; &lt;implicit&gt; &lt;style&gt; */
        ...
    }
    ...
</pre>
<p>It should be noted that this code precedes the advent of the
supporting generator package <b class="package"><a href="critcl_emap.html">critcl::emap</a></b>. using the
generator the definition of the mapping becomes much simpler:</p>
<pre class="doctools_example">
    critcl::emap::def yaml_sequence_style_t {
        any   0
        block 1
        flow  2
    }
</pre>
<p>Note that the generator will not only provide the conversions, but
also define the argument and result types needed for their use by
<b class="cmd">critcl::cproc</b>.
Another example of such a semi-trivial argument type can be found in
the <b class="package">CRIMP</b> package, which defines a <b class="type">Tcl_ObjType</b> for
<i class="term">image</i> values. This not only provides a basic argument type for
any image, but also derived types which check that the image has a
specific format. Here we see for the first time non-integer arguments,
and the need to define the C types used for variables holding the C
level value, and the type of function parameters (Due to C promotion
rules we may need different types).</p>
<pre class="doctools_example">
    critcl::argtype image {
        if (crimp_get_image_from_obj (interp, @@, &amp;@A) != TCL_OK) {
            return TCL_ERROR;
        }
    } crimp_image* crimp_image*
    ...
        set map [list &lt;&lt;type&gt;&gt; $type]
        critcl::argtype image_$type [string map $map {
            if (crimp_get_image_from_obj (interp, @@, &amp;@A) != TCL_OK) {
                return TCL_ERROR;
            }
            if (@A-&gt;itype != crimp_imagetype_find (&quot;crimp::image::&lt;&lt;type&gt;&gt;&quot;)) {
                Tcl_SetObjResult (interp,
                                  Tcl_NewStringObj (&quot;expected image type &lt;&lt;type&gt;&gt;&quot;,
                                                    -1));
                return TCL_ERROR;
            }
        }] crimp_image* crimp_image*
    ...
</pre>
</div>
<div id="subsection4" class="doctools_subsection"><h3><a name="subsection4">Custom Types, Support structures</a></h3>
<p>The adjunct command <b class="cmd">critcl::argtypesupport</b> is for when the
conversion needs additional definitions, for example a helper
structure.</p>
<p>An example of this can be found among the standard types of
critcl itself, the <b class="type">pstring</b> type. This type provides the C
function with not only the string pointer, but also the string length,
and the <b class="type">Tcl_Obj*</b> this data came from. As <b class="cmd">critcl::cproc</b>'s
calling conventions allow us only one argument for the data of the
parameter a structure is needed to convey these three pieces of
information.</p>
<p>Thus the argument type is defined as</p>
<pre class="doctools_example">
    critcl::argtype pstring {
        @A.s = Tcl_GetStringFromObj(@@, &amp;(@A.len));
        @A.o = @@;
    } critcl_pstring critcl_pstring
    critcl::argtypesupport pstring {
        typedef struct critcl_pstring {
            Tcl_Obj*    o;
            const char* s;
            int         len;
        } critcl_pstring;
    }
</pre>
<p>In the case of such a structure being large we may wish to
allocate it on the heap instead of having it taking space on the
stack. If we do that we need another adjunct command,
<b class="cmd">critcl::argtyperelease</b>. This command specifies the code required
to release dynamically allocated resources when the worker function
returns, before the shim returns to the caller in Tcl.
To keep things simple our example is synthetic, a modification of
<b class="const">pstring</b> above, to demonstrate the technique. An actual, but
more complex example is the code to support the variadic <i class="arg">args</i>
argument of <b class="cmd">critcl::cproc</b>.</p>
<pre class="doctools_example">
    critcl::argtype pstring {
        @A = (critcl_pstring*) ckalloc(sizeof(critcl_pstring));
        @A-&gt;s = Tcl_GetStringFromObj(@@, &amp;(@A-&gt;len));
        @A-&gt;o = @@;
    } critcl_pstring* critcl_pstring*
    critcl::argtypesupport pstring {
        typedef struct critcl_pstring {
            Tcl_Obj*    o;
            const char* s;
            int         len;
        } critcl_pstring;
    }
    critcl::argtyperelease pstring {
        ckfree ((char*)) @A);
    }
</pre>
<p>Note, the above example shows only the most simple case of an
allocated argument, with a conversion that cannot fail (namely, string
retrieval). If the conversion can fail then either the allocation has
to be defered to happen only on successful conversion, or the
conversion code has to release the allocated memory itself in the
failure path, because it will never reach the code defined via
<b class="cmd">critcl::argtyperelease</b> in that case.</p>
</div>
<div id="subsection5" class="doctools_subsection"><h3><a name="subsection5">Custom Types, Results</a></h3>
<p>All of the previous sections dealt with argument conversions,
i.e. going from Tcl into C.
Custom result types are for the reverse direction, from C to Tcl.
This is usually easier, as most of the time errors should not be
possible. Supporting structures, or allocating them on the heap are
not really required and therefore not supported.</p>
<p>The example of a result type shown below was pulled from
<b class="package">KineTcl</b>. It is a variant of the builtin result type
<b class="type">Tcl_Obj*</b>, aka <b class="type">object</b>. The builtin conversion assumes
that the object returned by the function has a refcount of 1 (or
higher), with the function having held the reference, and releases
that reference after placing the value into the interp result. The
conversion below on the other hand assumes that the value has a
refcount of 0 and thus that decrementing it is forbidden, lest it be
released much to early, and crashing the system.</p>
<pre class="doctools_example">
    critcl::resulttype KTcl_Obj* {
        if (rv == NULL) { return TCL_ERROR; }
        Tcl_SetObjResult(interp, rv);
        /* No refcount adjustment */
        return TCL_OK;
    } Tcl_Obj*
</pre>
<p>This type of definition is also found in <b class="package">Marpa</b> and recent
hacking hacking on <b class="package">CRIMP</b> introduced it there as well. Which
is why this definition became a builtin type starting with version
3.1.16, under the names <b class="type">Tcl_Obj*0</b> and <b class="type">object0</b>.</p>
<p>Going back to errors and their handling, of course, if a
function we are wrapping signals them in-band, then the conversion of
such results has to deal with that. This happens for example in
<b class="package">KineTcl</b>, where we find</p>
<pre class="doctools_example">
    critcl::resulttype XnStatus {
        if (rv != XN_STATUS_OK) {
            Tcl_AppendResult (interp, xnGetStatusString (rv), NULL);
            return TCL_ERROR;
        }
        return TCL_OK;
    }
    critcl::resulttype XnDepthPixel {
        if (rv == ((XnDepthPixel) -1)) {
            Tcl_AppendResult (interp,
                              &quot;Inheritance error: Not a depth generator&quot;,
                              NULL);
            return TCL_ERROR;
        }
        Tcl_SetObjResult (interp, Tcl_NewIntObj (rv));
        return TCL_OK;
    }
</pre>
</div>
<div id="subsection6" class="doctools_subsection"><h3><a name="subsection6">Handling A Variable Number Of Arguments</a></h3>
<p>In <span class="sectref"><a href="#subsection1">A Simple Procedure</a></span> we demonstrated how easy a
translation to C can be. Is it still as easy when we introduce
something moderately complex like handling a variable number of
arguments ? A feature which is needed to handle commands with options
and optional arguments ?</p>
<p>Well, starting with version 3.1.16 <b class="cmd">critcl::cproc</b> does
have full support for optional arguments, <i class="arg">args</i>-style variadics,
and default values, extending its range to everything covered by the
builtin <b class="cmd">proc</b>. The only thing not truly supported are options
(i.e. flag arguments) of any kind.</p>
<p>For the moment, and the example, let us pretend that we can use
<b class="cmd">critcl::cproc</b> only if the number of arguments is fully known
beforehand, i.e. at the time of declaration.
Then we have to use <b class="cmd">critcl::ccommand</b> to handle the translation
of the procedure shown below:</p>
<pre class="doctools_example">
    proc math {args} {
        set sum 0
        foreach y $args { set sum [expr {$sum + $y}] }
        return $sum
    }
</pre>
<p>Its advantage: Access to the low-level C arguments representing
the Tcl arguments of the command. Full control over argument
conversion, argument validation, etc.</p>
<p>Its disadvantage: Access to the low-level C arguments
representing the Tcl arguments of the command. Assuming the burden of
having to write argument conversion, argument validation, etc. Where
<b class="cmd">critcl::cproc</b> handles the task of converting from Tcl to C
values (for arguments) and back (for the result), with
<b class="cmd">critcl::command</b> it is the developer who has to write all this
code.</p>
<p>Under our restriction the translation of the example is:</p>
<pre class="doctools_example">
    critcl::ccommand math {cd ip oc ov} {
        double sum = 0;
        double y;
        oc --;
        while (oc) {
            if (Tcl_GetDoubleFromObj (ip, ov[oc], &amp;y) != TCL_OK) {
                return TCL_ERROR;
            }
            sum += y;
            oc --;
        }
        Tcl_SetObjResult (ip, Tcl_NewDoubleObj (sum));
        return TCL_OK:
    }
</pre>
<p>Notable about this translation:</p>
<ol class="doctools_enumerated">
<li><p>As promised/threatened, all the conversions between the Tcl and
       C domains are exposed, and the developer should know her way
       around Tcl's C API.</p></li>
<li><p>The four arguments &quot;cd ip oc ov&quot; are our names for the
low-level arguments holding</p>
<ol class="doctools_enumerated">
<li><p>ClientData (reference)</p></li>
<li><p>Tcl_Interp (reference)</p></li>
<li><p>Number of arguments, and</p></li>
<li><p>Array of argument values, each a Tcl_Obj*.</p></li>
</ol>
<p>This list of arguments, while not optional in itself, is allowed to be
empty, and/or to contain empty strings as argument names. If we do
that critcl will supply standard names for the missing pieces, namely:</p>
<ol class="doctools_enumerated">
<li><p>clientdata</p></li>
<li><p>interp</p></li>
<li><p>objc</p></li>
<li><p>objv</p></li>
</ol>
</li>
</ol>
<p>Now, letting go of our pretenses regarding the limitations of
<b class="cmd">critcl::cproc</b>, due to the support it does have for
<i class="arg">args</i>-style variadics (since version 3.1.16) we can write a much
simpler translation:</p>
<pre class="doctools_example">
    critcl::cproc math {double args} double {
        double sum = 0;
        args.c --;
        while (args.c) {
            sum += args.v[args.c];
            args.c --;
        }
        return sum;
    }
</pre>
</div>
<div id="subsection7" class="doctools_subsection"><h3><a name="subsection7">Data As A Tcl Command</a></h3>
<p>Here we assume that we have a Tcl procedure which returns a fixed
string. In the final product we are going to C to hide this string
from the casual user.</p>
<pre class="doctools_example">
    proc somedata {} {
	return {... A large blob of characters ...}
    }
</pre>
<p>The translation of this is simple and easy:</p>
<pre class="doctools_example">
    package require critcl
    critcl::cdata somedata {... A large blob of characters ...}
</pre>
<p>There is nothing really notable here.</p>
</div>
<div id="subsection8" class="doctools_subsection"><h3><a name="subsection8">Blocks of arbitrary C</a></h3>
<p>Often just defining Tcl commands in C, as demonstrated in the sections
<span class="sectref"><a href="#subsection1">A Simple Procedure</a></span>,
<span class="sectref"><a href="#subsection6">Handling A Variable Number Of Arguments</a></span>, and
<span class="sectref"><a href="#subsection7">Data As A Tcl Command</a></span>
is not really enough.
For example we may have several of our new C commands using the same
code over and over, and we wish avoid this duplication. Or we wish to
pull in declarations and definitions from some external library.</p>
<p>In both cases we require the ability to embed an unstructured block of
C code which can contain whatever we want, defines, functions,
includes, etc. without being directly tied to Tcl commands.
The command <b class="cmd">critcl::code</b> provides us with exactly that.
As our example now an excerpt taken from real code, the top of the
&quot;<b class="file">sha1c.tcl</b>&quot; critcl file in the <i class="term">sha1</i> module of
<i class="term">Tcllib</i>:</p>
<pre class="doctools_example">
    critcl::ccode {
        #include &quot;sha1.h&quot;
        #include &lt;stdlib.h&gt;
        #include &lt;assert.h&gt;
        static
        Tcl_ObjType sha1_type; /* fast internal access representation */
        static void
        sha1_free_rep(Tcl_Obj* obj)
        {
            SHA1_CTX* mp = (SHA1_CTX*) obj-&gt;internalRep.otherValuePtr;
            Tcl_Free(mp);
        }
        ...
    }
</pre>
<p>We see here the beginning of the C code defining a custom
<i class="term">Tcl_ObjType</i> holding the data of a SHA1 context used during the
incremental calculation of sha1 hashes.</p>
</div>
<div id="subsection9" class="doctools_subsection"><h3><a name="subsection9">Constant values</a></h3>
<p>While one might believe that there is no need for commands which
returns constant values that is not true. Commands reporting on
compile-time configuration, like version numbers, available features,
etc. are at least one use case for such commands.</p>
<p>The reason for creating critcl commands to support them ?
Convenience to the user, yes, but further than that, the ability to
optimize the internals, i.e. the generated code.</p>
<p>A <b class="cmd">cproc</b> would be easy to write, but incurs overhead due
to a superfluous work function. A <b class="cmd">ccommand</b> has no overhead,
except that of the user having to write the argument checking and
result conversion.</p>
<p>Using <b class="cmd">critcl::cconst</b> is both convenient and without code
overhead.
Our example is a function found in package <b class="package">tcl-linenoise</b>,
that is, if <b class="cmd">cconst</b> had existed at the time of writing. It
returns a configuration value reporting to the policy layer if an
extended mode for hidden input is available from the bound
<b class="package">linenoise</b>, or not.</p>
<pre class="doctools_example">
    critcl::cconst linenoise::hidden_extended boolean 1
</pre>
</div>
<div id="subsection10" class="doctools_subsection"><h3><a name="subsection10">Lifting constants</a></h3>
<p>When writing a critcl-based package to make a third-party library
available to scripts we do not only have to make the relevant
functions available as commands, often we also have to know all
the various constants, flags, etc. these functions take.</p>
<p>Rather than writing such magic numbers directly we would
greatly prefer to use symbolic names instead.
Instead of providing one or more commands to list and map the magic
numbers to strings critcl <em>only</em> provides a single command which
allows the export of C defines and enumeration values, mapping them to
Tcl variables of the given names, whose values are the associated
magic numbers.</p>
<p>This is good enough because the developers of the third-party
library were very likely like us and wanted to use symbolic names
instead of magic numbers. Which in C are declared as via defines and
enumeration types. We just have to <em>lift</em> them up.</p>
<p>Our example comes from <b class="package">cryptkit</b>, a Tcl binding to
<b class="package">cryptlib</b>, a cryptography library.
The command</p>
<pre class="doctools_example">
    critcl::cdefines CRYPT_* ::crypt
</pre>
<p>maps all Cryptlib specific #defines and enums into the namespace
<b class="namespace">::crypt</b>, telling critcl to create aliases to the symbols.</p>
<p>Similarly</p>
<pre class="doctools_example">
    critcl::cdefines {
        NULL
        TRUE
        FALSE
        TCL_OK
        TCL_ERROR
    } ::crypt
</pre>
<p>maps the listed defines into the namespace <b class="namespace">::crypt</b>.</p>
<p>An <em>important</em> thing to note:
These commands <em>do not create</em> the defines in the C level. They
only lift pre-existing material.
Which can come from the headers of the third-party library, the usual
case, but also from <span class="sectref"><a href="#subsection8">Blocks of arbitrary C</a></span>.</p>
<p>A corrollary to the above: What is not where, cannot be
lifted. All listed names and patterns which have no actual C code
declaring them are ignored, i.e. not mapped.</p>
</div>
<div id="subsection11" class="doctools_subsection"><h3><a name="subsection11">Finding header files</a></h3>
<p>A notable thing in the example shown in the section about
<span class="sectref"><a href="#subsection8">Blocks of arbitrary C</a></span> is the</p>
<pre class="doctools_example">
    #include &quot;sha1.h&quot;
</pre>
<p>statement. Where does this header come from ?
Looking at the Tcllib module we will find that the header is actually
a sibling to the &quot;<b class="file">sha1c.tcl</b>&quot; file containing the embedded C code.
However, <b class="package"><a href="critcl_pkg.html">critcl</a></b> does not know that. It has to be told.
While without that knowledge it will invoke the compiler just fine,
the compilation will fail because the header is not on the include
paths used by the compiler, and therefore will not be found.</p>
<p>For this we have the <b class="cmd">critcl::cheaders</b> command. It enables us to
either tell the compiler the path(s) where the required headers can be
found, using</p>
<pre class="doctools_example">
    critcl::cheaders -I/path/to/headers/
</pre>
<p>or to tell it directly which headers we are using and where they live:</p>
<pre class="doctools_example">
    critcl::cheaders sha1.h
</pre>
<p>And now critcl knows that &quot;<b class="file">sha1.h</b>&quot; is important, and that it
lives besides the &quot;<b class="file">.critcl</b>&quot; file which referenced it (because of
the relative path used).
<em>Note</em> that this doesn't absolve us of the need to &quot;#include&quot; the
header through a <b class="cmd">critcl::ccode</b> block. This only tells critcl
where it lives so that it can configure the compiler with the proper
include paths to actually find it on use.</p>
<p>Further note that a C development environment is usually
configured to find all the system headers, obviating the need for a
<b class="cmd">critcl::cheaders</b> declaration when such are used. For these a
plain &quot;#include&quot; in a <b class="cmd">critcl::ccode</b> block is good enough.
In other words, the second form of invoking <b class="cmd">critcl::cheaders</b> is
pretty much only for headers which accompany the &quot;<b class="file">.critcl</b>&quot; file.</p>
</div>
<div id="subsection12" class="doctools_subsection"><h3><a name="subsection12">Separate C sources</a></h3>
<p>In all of the examples shown so far the C code was fully embedded in a
&quot;<b class="file">.critcl</b>&quot; file. However, if the C part is large it can make sense
to break it out of the &quot;<b class="file">.critcl</b>&quot; file into one or more separate
proper &quot;<b class="file">.c</b>&quot; file(s).</p>
<p>The <b class="cmd">critcl::csources</b> command can then be used to make
this code known to the original &quot;<b class="file">.critcl</b>&quot; file again.
This command accepts the paths to the &quot;<b class="file">.c</b>&quot; files as arguments,
and glob patterns as well.
Our example comes from the <b class="package">struct::graph</b> package in
Tcllib.
Its core C functions are in separate files, and the &quot;<b class="file">.critcl</b>&quot;
code then makes them known via:</p>
<pre class="doctools_example">
namespace eval ::struct {
    # Supporting code for the main command.
    critcl::cheaders graph/*.h
    critcl::csources graph/*.c
    ...
}
</pre>
<p>which tells critcl that these files are in the subdirectory
&quot;<b class="file">graph</b>&quot; relative to the location of &quot;<b class="file">graph_c.tcl</b>&quot;, which is
the relevant &quot;<b class="file">.critcl</b>&quot; file.</p>
<p>This example also demonstrates again the use of
<b class="cmd">critcl::cheaders</b>, which we also saw in section
<span class="sectref"><a href="#subsection11">Finding header files</a></span>.</p>
</div>
<div id="subsection13" class="doctools_subsection"><h3><a name="subsection13">Finding external libraries</a></h3>
<p>When creating a package exposing some third-party library to Tcl
<span class="sectref"><a href="#subsection11">Finding header files</a></span> is only the first part, to enable
failure-free compilation. We also have to find the library/ies
themselves so that they can be linked to our package. This is
described here. The last issue, <span class="sectref"><a href="#subsection10">Lifting constants</a></span> from C
to Tcl for the use by scripts is handled in a separate section and
example.</p>
<p>The relevant command is <b class="cmd">critcl::clibraries</b>. Its basic
semantics are like that of <b class="cmd">critcl::cheaders</b>, i.e. It enables us
to tell the linker the path(s) where the required libraries can be
found, using</p>
<pre class="doctools_example">
    critcl::clibraries -L/path/to/libraries/
</pre>
<p>name them</p>
<pre class="doctools_example">
    critcl::clibraries -lfoo
</pre>
<p>or tell it directly which libraries we are using and where they live:</p>
<pre class="doctools_example">
    critcl::clibraries /path/to/library/foo.so
</pre>
<p>This last way of using should be avoided however, as it intermingles
searching and naming, plus the name is platform dependent.</p>
<p>For OS X we additionally have the <b class="cmd">critcl::framework</b>
command which enables us to name the frameworks used by our package.
Note that this command can be used unconditionally. If the build
target is not OS X it is ignored.</p>
</div>
<div id="subsection14" class="doctools_subsection"><h3><a name="subsection14">Customizing the compile and link steps</a></h3>
<p>The commands <b class="cmd">critcl::cflags</b> and <b class="cmd">critcl::ldflags</b> enable you
to provide custom options to the compile and link phases for a
&quot;<b class="file">.critcl</b>&quot; file.</p>
<p>This usually becomes necessary if the C code in question comes
from an external library we are writing a Tcl binding for, with
multiple configurations to select, non-standard header locations, and
other things.
Among the latter, especially platform-specific settings, for example
byteorder.</p>
<p>This makes <b class="cmd">critcl::check</b> an important adjunct command, as
this is the API for <span class="sectref"><a href="#subsection20">Checking The Environment</a></span>, and then
selecting the compile &amp; link flags to use.</p>
<p><em>I currently have no specific example to demonstrate these commands.</em></p>
</div>
<div id="subsection15" class="doctools_subsection"><h3><a name="subsection15">Having both C and Tcl functionality</a></h3>
<p>Often enough only pieces of a package require recoding in C to boost
the whole system. Or, alternatively, the package in question consists
of a low-level layer C with a Tcl layer above encoding policies and
routing to the proper low-level calls, creating a nicer (high-level)
API to the low-level functionality, etc.</p>
<p>For all of this we have to be able to write a package which
contains both C and Tcl, nevermind the fact the C parts are embedded
in Tcl.</p>
<p>The easiest way to structure such a package is to have several
files, each with a different duty. First, a &quot;<b class="file">.critcl</b>&quot; file
containing the embedded C, and second one or more &quot;<b class="file">.tcl</b>&quot; files
providing the Tcl parts.
Then use the <b class="cmd">critcl::tsources</b> command in the &quot;<b class="file">.critcl</b>&quot; file
to link the two parts together, declaring the &quot;<b class="file">.tcl</b>&quot; files as
necessary companions of the C part.</p>
<pre class="doctools_example">
    package require critcl
    critcl::tsources your-companion.tcl ; # Companion file to use
    ... embedded C via critcl commands ...
</pre>
<p>With a declaration as shown above the companion file will be
automatically <b class="cmd">source</b>d when the C parts are made available, thus
making the Tcl parts available as well.</p>
</div>
<div id="subsection16" class="doctools_subsection"><h3><a name="subsection16">Using C with Tcl functionality as fallback</a></h3>
<p>There is one special case of
<span class="sectref"><a href="#subsection15">Having both C and Tcl functionality</a></span>
which deserves its own section.</p>
<p>The possibility of not having the fast C code on some platform,
and using a slower Tcl implementation of the functionality. In other
words, a fallback which keeps the package working in the face of
failure to build the C parts. A more concrete example of this would be
a module implementing the SHA hash, in both C and Tcl, and using the
latter if and only if the C implementation is not available.</p>
<p>There two major possibilities in handling such a situation.</p>
<ol class="doctools_enumerated">
<li><p>Keep all the pieces separated. In that scenario our concrete
example would be spread over three packages. Two low-level packages
<b class="package">sha::c</b> and <b class="package">sha::tcl</b> containing the two
implementations of the algorithm, and, thirdly, a coordinator package
<b class="package">sha</b> which loads either of them, based on availability.</p>
<p>The Tcllib bundle of packages contains a number of packages
structured in this manner, mostly in the <i class="term">struct</i> module.</p>
<p>Writing the C and Tcl parts should be simple by now, with all
the examples we had so far. The only non-trivial part is the
coordinator, and even that if and only if we wish to make it easy to
write a testsuite which can check both branches, C, and Tcl without
gymnastics. So, the most basic coordinator would be</p>
<pre class="doctools_example">
    set sha::version 1
    if {[catch {
        package require sha::c $sha::version
    }]} {
        package require sha::tcl $sha::version
    }
    package provide sha $sha::version
</pre>
<p>It tries to load the C implementation first, and falls back to the Tcl
implementation if that fails. The code as is assumes that both
implementations create exactly the same command names, leaving the
caller unaware of the choice of implementations.</p>
<p>A concrete example of this scheme can be found in Tcllib's
<b class="package">md5</b> package. While it actually uses ythe <b class="package">Trf</b> as
its accelerator, and not a critcl-based package the principle is the
same. It also demonstrates the need for additional glue code when the
C implementation doesn't exactly match the signature and semantics of
the Tcl implementation.</p>
<p>This basic coordinator can be easily extended to try more than
two packages to get the needed implementation. for example, the C
implementation may not just exist in a sha::c package, but also
bundled somewhere else. Tcllib, for example, has a tcllibc package
which bundles all the C parts of its packages which have them in a
single binary.</p>
<p>Another direction to take it in is to write code which allows
the loading of multiple implementations at the same time, and then
switching between them at runtime. Doing this requires effort to keep
the implementations out of each others way, i.e. they cannot provide
the same command names anymore, and a more complex coordinator as
well, which is able to map from the public command names to whatever
is provided by the implementation.</p>
<p>The main benefit of this extension is that it makes testing the
two different implementations easier, simply run through the same set
of tests multiple times, each time with different implementation
active. The disadvantage is the additional complexity of the
coordinator's internals. As a larger example of this technique here is
the coordinator &quot;<b class="file">modules/struct/queue.tcl</b>&quot; handling the C and Tcl
implementations of Tcllib's <b class="package">struct::queue</b> package:</p>
<pre class="doctools_example">
    # queue.tcl --
    #       Implementation of a queue data structure for Tcl.
    package require Tcl 8.4
    namespace eval ::struct::queue {}
    ## Management of queue implementations.
    # ::struct::queue::LoadAccelerator --
    #       Loads a named implementation, if possible.
    proc ::struct::queue::LoadAccelerator {key} {
        variable accel
        set r 0
        switch -exact -- $key {
            critcl {
                # Critcl implementation of queue requires Tcl 8.4.
                if {![package vsatisfies [package provide Tcl] 8.4]} {return 0}
                if {[catch {package require tcllibc}]} {return 0}
                set r [llength [info commands ::struct::queue_critcl]]
            }
            tcl {
                variable selfdir
                if {
                    [package vsatisfies [package provide Tcl] 8.5] &amp;&amp;
                    ![catch {package require TclOO}]
                } {
                    source [file join $selfdir queue_oo.tcl]
                } else {
                    source [file join $selfdir queue_tcl.tcl]
                }
                set r 1
            }
            default {
                return -code error &quot;invalid accelerator/impl. package $key: must be one of [join [KnownImplementations] {, }]&quot;
            }
        }
        set accel($key) $r
        return $r
    }
    # ::struct::queue::SwitchTo --
    #       Activates a loaded named implementation.
    proc ::struct::queue::SwitchTo {key} {
        variable accel
        variable loaded
        if {[string equal $key $loaded]} {
            # No change, nothing to do.
            return
        } elseif {![string equal $key &quot;&quot;]} {
            # Validate the target implementation of the switch.
            if {![info exists accel($key)]} {
                return -code error &quot;Unable to activate unknown implementation \&quot;$key\&quot;&quot;
            } elseif {![info exists accel($key)] || !$accel($key)} {
                return -code error &quot;Unable to activate missing implementation \&quot;$key\&quot;&quot;
            }
        }
        # Deactivate the previous implementation, if there was any.
        if {![string equal $loaded &quot;&quot;]} {
            rename ::struct::queue ::struct::queue_$loaded
        }
        # Activate the new implementation, if there is any.
        if {![string equal $key &quot;&quot;]} {
            rename ::struct::queue_$key ::struct::queue
        }
        # Remember the active implementation, for deactivation by future
        # switches.
        set loaded $key
        return
    }
    # ::struct::queue::Implementations --
    #       Determines which implementations are
    #       present, i.e. loaded.
    proc ::struct::queue::Implementations {} {
        variable accel
        set res {}
        foreach n [array names accel] {
            if {!$accel($n)} continue
            lappend res $n
        }
        return $res
    }
    # ::struct::queue::KnownImplementations --
    #       Determines which implementations are known
    #       as possible implementations.
    proc ::struct::queue::KnownImplementations {} {
        return {critcl tcl}
    }
    proc ::struct::queue::Names {} {
        return {
            critcl {tcllibc based}
            tcl    {pure Tcl}
        }
    }
    ## Initialization: Data structures.
    namespace eval ::struct::queue {
        variable  selfdir [file dirname [info script]]
        variable  accel
        array set accel   {tcl 0 critcl 0}
        variable  loaded  {}
    }
    ## Initialization: Choose an implementation,
    ## most preferred first. Loads only one of the
    ## possible implementations. And activates it.
    namespace eval ::struct::queue {
        variable e
        foreach e [KnownImplementations] {
            if {[LoadAccelerator $e]} {
                SwitchTo $e
                break
            }
        }
        unset e
    }
    ## Ready
    namespace eval ::struct {
        # Export the constructor command.
        namespace export queue
    }
    package provide struct::queue 1.4.2
</pre>
<p>In this implementation the coordinator renames the commands of the
low-level packages to the public commands, making the future dispatch
as fast as if the commands had these names anyway, but also forcing a
spike of bytecode recompilation if switching is ever done at the
runtime of an application, and not just used for testing, and possibly
disrupting introspection by the commands, especially if they move
between different namespaces.</p>
<p>A different implementation would be to provide the public
commands as procedures which consult a variable to determine which of
the loaded implementations is active, and then call on its
commands. This doesn't disrupt introspection, nor does it trigger
bytecode recompilation on switching. But it takes more time to
dispatch to the actual implementation, in every call of the public API
for the package in question.</p>
<p>A concrete example of this scheme can be found in Tcllib's
<b class="package">crc32</b> package.</p></li>
<li><p>Mix the pieces together. Please note that while I am describing
how to make this work I strongly prefer and recommend to use the
previously shown approach using separate files/packages. It is much
easier to understand and maintain. With this warning done, lets go
into the nuts and bolts.</p>
<p>If we care only about mode &quot;compile &amp; run&quot; things are easy:</p>
<pre class="doctools_example">
    package require critcl
    if {![critcl::compiling]} {
        proc mycommand {...} {
            ...
        }
    } else {
        critcl::cproc mycommand {...} {
            ...
        }
    }
</pre>
<p>The command <b class="cmd">critcl::compiling</b> tells us whether we have a
compiler available or not, and in the latter case we implement our
command in Tcl.</p>
<p>Now what happens when we invoke mode &quot;generate package&quot; ?
... compiler failure ...
... ok   - C code - everything fine
... fail - no package ? or just no C code ? declare self as tsource, to be used ?
... platform-specific C/Tcl -- uuid.</p></li>
</ol>
</div>
<div id="subsection17" class="doctools_subsection"><h3><a name="subsection17">Unlazy Packages</a></h3>
<p>By default critcl is a bit inconsistent between modes &quot;compile &amp; run&quot;
and &quot;generate package&quot;. The result of the latter is a standard Tcl
package which loads and sources all of its files immediately when it
is required. Whereas &quot;compile &amp; run&quot; defers actual compilation,
linking, and loading until the first time one of the declared commands
is actually used, making this very lazy.</p>
<p>This behaviour can be quite unwanted if Tcl companion files, or
other users of the C commands use introspection to determine the
features they have available. Just using [<b class="cmd">info commands</b>]
doesn't cut it, the <b class="variable">auto_index</b> array has to be checked as well,
making things quite inconvenient for the users.</p>
<p>To fix this issue at the source, instead of in each user, be it
inside of the package itself, or other packages, we have the command
<b class="cmd">critcl::load</b>.
Used as the last command in a &quot;<b class="file">.critcl</b>&quot; file it forces the
compile, link, and load trinity, ensuring that all C commands are
available immediately.</p>
<pre class="doctools_example">
    package require critcl
    ... Declare C procedures, commands, etc.
    critcl::load ; # Force build and loading.
</pre>
<p>Note that is not allowed, nor possible to use critcl commands
declaring anything after <b class="cmd">critcl::load</b> has been called. I.e., code like</p>
<pre class="doctools_example">
    package require critcl
    ... Declare C procedures, commands, etc.
    critcl::load ; # Force build and loading.
    ... More declarations of C code, ...
    critcl::code { ... }
</pre>
<p>will result in an error. The only package-related commands still
allowed are</p>
<ol class="doctools_enumerated">
<li><p><b class="cmd">critcl::done</b></p></li>
<li><p><b class="cmd">critcl::failed</b></p></li>
<li><p><b class="cmd">critcl::load</b></p></li>
</ol>
<p>as these only query information, namely the build status, and are
protected against multiple calls.</p>
</div>
</div>
<div id="section3" class="doctools_section"><h2><a name="section3">Checking your C</a></h2>
<p>As said several times, by default critcl defers the compile and link
steps for a file until it is needed, i.e. the first command of the
&quot;<b class="file">.critcl</b>&quot; file in question is actually invoked.</p>
<p>This not only has the effect of lazily loading the package's
functionality, but also, when developing using mode &quot;compile &amp; run&quot;,
of us not seeing any errors in our code until we are actually trying
to run some demonstration.</p>
<p>If we do not wish to have such a delay we have to be able to
force at least the execution of the compile step.</p>
<p>The command <b class="cmd">critcl::failed</b> is exactly that. When called
it forcibly builds the C code for the &quot;<b class="file">.critcl</b>&quot; file it is part
of, and returns a boolean vlaue signaling failure (<b class="const">true</b>), or
success (<b class="const">false</b>).</p>
<pre class="doctools_example">
    package require critcl
    ... Declare C procedures, commands, etc.
    if {[critcl::failed]} {
        ... signal error
    }
</pre>
<p>It is related and similar to <b class="cmd">critcl::load</b>, the command to
overcome the lazy loading, as shown in section
<span class="sectref"><a href="#subsection17">Unlazy Packages</a></span>.</p>
<p>Like it is not allowed, nor possible to use critcl commands
declaring anything after <b class="cmd">critcl::failed</b> has been called, making
it pretty much the last critcl command in a &quot;<b class="file">.critcl</b>&quot; file.
Code like</p>
<pre class="doctools_example">
    package require critcl
    ... Declare C procedures, commands, etc.
    if {[critcl::failed]} { ... }
    ... More declarations of C code, ...
    critcl::code { ... }
</pre>
<p>will result in an error. The only package-related commands still
allowed are</p>
<ol class="doctools_enumerated">
<li><p><b class="cmd">critcl::done</b></p></li>
<li><p><b class="cmd">critcl::failed</b></p></li>
<li><p><b class="cmd">critcl::load</b></p></li>
</ol>
<p>as these only query information, namely the build status, and are
protected against multiple calls.</p>
<div id="subsection18" class="doctools_subsection"><h3><a name="subsection18">Which Tcl ?</a></h3>
<p>When building the shared library from the embedded C sources one of
the things critcl does for us is to provide the Tcl headers,
especially the stubs declarations.</p>
<p>By default these are the Tcl 8.4 headers and stubs, which
covers 90% of the cases. What when the package in question is meant
for use with Tcl 8.5 or higher, using C-level features of this version
of Tcl.</p>
<p>Use the <b class="cmd">critcl::tcl</b> command to declare to critcl the
minimum version of Tcl required to operate the package. This can be
either <b class="const">8.4</b>, <b class="const">8.5</b>, or <b class="const">8.6</b>, and critcl then
supplies the proper headers and stubs.</p>
<pre class="doctools_example">
    package require critcl
    critcl::tcl 8.5
    ... Declare your code ...
</pre>
</div>
<div id="subsection19" class="doctools_subsection"><h3><a name="subsection19">Making A Widget</a></h3>
<p>... requires compiling against the Tk headers, and linking with Tk's
stubs. For our convenience we have a simple, single command to
activate all the necessary machinery, with critcl supplying the header
files and stubs C code, instead of having to make it work on our own
via <b class="cmd">critcl::cflags</b>, <b class="cmd">critcl::ldflags</b>,
<b class="cmd">critcl::cheaders</b>, <b class="cmd">critcl::csources</b>.</p>
<p>This command is <b class="cmd">critcl::tk</b>.</p>
<pre class="doctools_example">
    package require critcl
    critcl::tk ; # And now critcl knows to put in the Tk headers and other support.
    ... Declare your code ...
</pre>
<p>Please note that this doesn't release you from the necessity of
learning Tk's C API and how to use it to make a widget work. Sorry.</p>
</div>
<div id="subsection20" class="doctools_subsection"><h3><a name="subsection20">Checking The Environment</a></h3>
<p>... may be necessary when creating a binding to some third-party
library. The headers for this library may be found in non-standard
locations, ditto for the library/ies itself. We may not have the
headers and/or library on the build host. Types with
platform-dependent sizes and definitions. Endianness issues. Any number
of things.</p>
<p>TEA-based packages can use <b class="syscmd">autoconf</b> and various
predefined macros to deal with all this.
We have the <i class="term">Power Of Tcl (tm)</i> and <b class="cmd">critcl::check</b>.</p>
<p>This command takes a piece of C code as argument, like
<b class="cmd">critcl::ccode</b>. Instead of saving it for later it however tries
to compile it immediately, using the current settings, and then
returns a boolean value reporting on the success (<b class="const">true</b>) or
failure (<b class="const">false</b>). From there we can then branch to different
declarations.</p>
<p>As example let us check for the existence of some header
&quot;<b class="file">FOO.h</b>&quot;:</p>
<pre class="doctools_example">
    package require critcl
    if {[critcl::check {
        #include &lt;FOO.h&gt;
    }]} {
        ... Code for when FOO.h is present.
    } else {
        ... Code for when FOO.h is not present.
    }
</pre>
<p>Should we, on the other hand, wish to search for the header ourselves,
in non-standard locations we have the full power of Tcl available,
i.e. loops, the <b class="cmd">file</b> and <b class="cmd">glob</b> commands, etc., which can
then be followed by a <b class="cmd">critcl::cheader</b> command to declare the
location we found (See also <span class="sectref"><a href="#subsection11">Finding header files</a></span>).</p>
<p>A nice extension to critcl would be a package collecting
pocedures for common tasks like that, sort of like an
<b class="syscmd">autoconf</b> for Tcl. <b class="package">critcl::config</b> seems to be nice
name for such a package.</p>
<p>Obvious adjunct commands which can be driven by results from
<b class="cmd">critcl::check</b> are</p>
<dl class="doctools_definitions">
<dt><b class="cmd">critcl::cflags</b></dt>
<dd></dd>
<dt><b class="cmd">critcl::cheaders</b></dt>
<dd></dd>
<dt><b class="cmd">critcl::clibraries</b></dt>
<dd></dd>
<dt><b class="cmd">critcl::framework</b></dt>
<dd></dd>
<dt><b class="cmd">critcl::ldflags</b></dt>
<dd></dd>
</dl>
<p>Less obvious, yet still valid are also</p>
<dl class="doctools_definitions">
<dt><b class="cmd">critcl::ccode</b></dt>
<dd></dd>
<dt><b class="cmd">critcl::ccommand</b></dt>
<dd></dd>
<dt><b class="cmd">critcl::cdata</b></dt>
<dd></dd>
<dt><b class="cmd">critcl::cproc</b></dt>
<dd></dd>
<dt><b class="cmd">critcl::csources</b></dt>
<dd></dd>
<dt><b class="cmd">critcl::ctsources</b></dt>
<dd></dd>
</dl>
<p>and pretty much everything else you can imagine.</p>
</div>
<div id="subsection21" class="doctools_subsection"><h3><a name="subsection21">License Invoked</a></h3>
<p>When writing packages it is always good manners to provide prospective
users with the license the package is under, so that they can decide
whether they truly want to use the package, or not.</p>
<p>As critcl-based packages often consist of only a single file a
nice way of doing that is to embed the license in that file. By using
a critcl command, namely <b class="cmd">critcl::license</b> this information is
then also available to the critcl application, which can put it into a
standard location, i.e. &quot;<b class="file">license.terms</b>&quot;, of the generated
packages.</p>
<p><em>I currently have no specific example to demonstrate the command.</em></p>
</div>
</div>
<div id="section4" class="doctools_section"><h2><a name="section4">Building Critcl Packages</a></h2>
<p>This is the section for developers having to generate packages from
&quot;<b class="file">.critcl</b>&quot; files, i.e binaries for deployment,</p>
<div id="subsection22" class="doctools_subsection"><h3><a name="subsection22">Getting Help ...</a></h3>
<p>... Is easy. Running</p>
<pre class="doctools_example">
    critcl -help
</pre>
<p>prints the basics of using the application to <b class="const">stdout</b>.</p>
</div>
<div id="subsection23" class="doctools_subsection"><h3><a name="subsection23">Pre-Filling The Result Cache</a></h3>
<p>The default mode of the <b class="cmd"><a href="critcl_pkg.html">critcl</a></b> application is to take a series
of &quot;<b class="file">.critcl</b>&quot; files, build their binaries, and leave them behind
in the result cache. When the files are later actually used the
compile and link steps can be skipped, leading to shorter load times.</p>
<p>The command line for this is</p>
<pre class="doctools_example">
    critcl foo.tcl
</pre>
<p>or, to process multiple files</p>
<pre class="doctools_example">
    critcl foo.tcl bar.tcl ...
</pre>
<p>One thing to be aware of, should <b class="cmd"><a href="critcl_pkg.html">critcl</a></b> find that the cache
already contains the results for the input files, no building will be
done. If you are sure that these results are outdated use the option
<b class="option">-force</b> to force(sic!) <b class="cmd"><a href="critcl_pkg.html">critcl</a></b> to rebuild the binaries.</p>
<pre class="doctools_example">
    critcl -force foo.tcl
</pre>
<p>For debugging purposes it may be handy to see the generated
intermediate &quot;<b class="file">.c</b>&quot; files as well. Their removal from the cache can
be prevented by specifying the option <b class="option">-keep</b>.</p>
<pre class="doctools_example">
    critcl -keep foo.tcl
</pre>
<p>These can be combined, of course.</p>
</div>
<div id="subsection24" class="doctools_subsection"><h3><a name="subsection24">Building A Package</a></h3>
<p>To build the binary package for a &quot;<b class="file">.critcl</b>&quot; file, instead of
<span class="sectref"><a href="#subsection23">Pre-Filling The Result Cache</a></span>, simply specify the option
<b class="option">-pkg</b>.</p>
<pre class="doctools_example">
    critcl -pkg foo.tcl
</pre>
<p>This will geneate a package named <b class="package">foo</b>.
A simpler alternative to the above is</p>
<pre class="doctools_example">
    critcl -pkg foo
</pre>
<p>The application will automatically assume that the input file to look
for is &quot;<b class="file">foo.tcl</b>&quot;.</p>
<p>But what when the name of the input file is not the name of the
package to build ? This we can handle as well:</p>
<pre class="doctools_example">
    critcl -pkg foo bar.tcl
</pre>
<p>The argument <b class="package">foo</b> specifies the name, and &quot;<b class="file">bar.tcl</b>&quot; is
the file to process.</p>
<p>Going back to the very first example, it is of course possible to use
an absolute path to specify the file to process:</p>
<pre class="doctools_example">
    critcl -pkg /path/to/foo.tcl
</pre>
<p>The package name derived from that is still <b class="package">foo</b>.</p>
</div>
<div id="subsection25" class="doctools_subsection"><h3><a name="subsection25">Building And Installing A Package</a></h3>
<p>Here we assume that you know the basics of how to build a package.
If not, please read section <span class="sectref"><a href="#subsection24">Building A Package</a></span> first.</p>
<p>By default <b class="cmd"><a href="critcl_pkg.html">critcl</a></b> will place all newly-made packages in the
subdirectory &quot;<b class="file">lib</b>&quot; of the current working directory.
I.e. running</p>
<pre class="doctools_example">
    critcl -pkg foo
</pre>
<p>will create the directory &quot;<b class="file">lib/foo</b>&quot; which contains all the files
of the package.</p>
<p>When this behaviour is unwanted the option <b class="option">-libdir</b> is available,
allowing the explicit specification of the destination location to use.</p>
<pre class="doctools_example">
    critcl -pkg -libdir /path/to/packages foo
</pre>
<p>A common use might be to not only build the package in question, but
to also immediately install it directly in the path where the user's
<b class="cmd">tclsh</b> will be able to find it.
Assuming, for example, that the <b class="cmd">tclsh</b> in question is installed
at &quot;<b class="file">/path/to/bin/tclsh</b>&quot;, with the packages searched for under
&quot;<b class="file">/path/to/lib</b>&quot; ([<b class="cmd">info library</b>]), the command</p>
<pre class="doctools_example">
    critcl -pkg -libdir /path/to/lib foo
</pre>
<p>will build the package and place it in the directory
&quot;<b class="file">/path/to/lib/foo</b>&quot;.</p>
</div>
<div id="subsection26" class="doctools_subsection"><h3><a name="subsection26">Building For Debugging</a></h3>
<p>Here we assume that you know the basics of how to build a package.
If not, please read section <span class="sectref"><a href="#subsection24">Building A Package</a></span> first.</p>
<p>An important issue, when there is trouble with the package, debugging
becomes necessary a evil.
Critcl supports this through the <b class="option">-debug</b> option.
Using it enables various build modes which help with that.</p>
<p>For example, to activate the Tcl core's built-in memory debugging
subsystem build your package with</p>
<pre class="doctools_example">
    critcl -pkg -debug memory foo
</pre>
<p>The resulting binary for package <b class="package">foo</b> will use Tcl's
debug-enabled (de)allocation functions, making them visible to Tcl's
<b class="cmd">memory</b> command. This of course assumes that the Tcl core used
was also built for memory debugging.</p>
<p>Further, built your package with</p>
<pre class="doctools_example">
    critcl -pkg -debug symbols foo
</pre>
<p>to see the <b class="package">foo</b>'s symbols (types, functions, variables, etc.)
when inspecting a &quot;<b class="file">core</b>&quot; file it is involved in with a symbolic
debugger,</p>
<p>To activate both memory debugging and symbols use either</p>
<pre class="doctools_example">
    critcl -pkg -debug all foo
</pre>
<p>or</p>
<pre class="doctools_example">
    critcl -pkg -debug symbols -debug memory foo
</pre>
</div>
<div id="subsection27" class="doctools_subsection"><h3><a name="subsection27">Retargeting The Binaries</a></h3>
<p>The configuration settings <b class="cmd"><a href="critcl_pkg.html">critcl</a></b> uses to drive the compiler,
linker, etc. are by default selected based on the platform it is run
on, to generate binaries which properly work on this platform.</p>
<p>There is one main use-case for overriding this selection, which is
done with the option <b class="option">-target</b>:</p>
<ol class="doctools_enumerated">
<li><p>Cross-compilation. The building of binaries for a platform T
while critcl actually runs on platform B.
The standard configuration of <b class="cmd"><a href="critcl_pkg.html">critcl</a></b> currently has settings for
two cross-compilation targets. So, to build 32bit Windows binaries on
a Linux host which has the Xmingw cross-compilation development
environment installed use</p>
<pre class="doctools_example">
    critcl -pkg -target mingw32 foo
</pre>
<p>Similarly, building a package for use on ARM processors while critcl
is running in an Intel environment use</p>
<pre class="doctools_example">
    critcl -pkg -target linux-arm foo
</pre>
<p>Note that both configurations assume that the cross-compiling
compiler, linke, etc. are found first in the <b class="variable">PATH</b>.</p></li>
</ol>
</div>
<div id="subsection28" class="doctools_subsection"><h3><a name="subsection28">Custom Configurations</a></h3>
<p>The compiler configurations coming with <b class="package"><a href="critcl_pkg.html">critcl</a></b> currently
cover all hosts having <b class="syscmd">gcc</b> installed (the foremost among
these are Linux and OS X), plus the native compilers of the more
common unix-like operating systems, i.e. Solaris, HP-UX, and AIX, and,
on the non-unix side, Windows.</p>
<p>Developers using operating systems and compilers outside of this range
will either have to install a <b class="syscmd">gcc</b>-based development
environment, i.e. get into the covered range, or write their own
custom configuration and then tell <b class="cmd"><a href="critcl_pkg.html">critcl</a></b> about it.</p>
<p>The latter is the easier part, given that <b class="cmd"><a href="critcl_pkg.html">critcl</a></b> supports the
option <b class="option">-config</b> whose argument is the path to the file
containing the custom configuration(s). I.e.</p>
<pre class="doctools_example">
    critcl -config /path/to/config ...
</pre>
<p>will run <b class="cmd"><a href="critcl_pkg.html">critcl</a></b> with the custom configuration in
&quot;<b class="file">/path/to/config</b>&quot;, with the other options and arguments as
explained in previous sections. Depending on the choice of name for
the new configuration(s) this may or may not require a
<b class="option">-target</b> option to select the configuration needed.</p>
<p>For the former, the writing of the custom configuration, the reader is
refered to the section &quot;Configuration Internals&quot; of the
<i class="term">CriTcl Package Reference</i> for the necessary details.
This is an advanced topic pretty much out of scope for this tutorial
beyond what was already said.</p>
</div>
<div id="subsection29" class="doctools_subsection"><h3><a name="subsection29">Custom Header Path</a></h3>
<p>Sometimes the use of <b class="cmd">critcl::headers</b> might not be enough for a
package to find its headers. Maybe they are outside of the paths
checked by the setup code.
To help the application recognizes the option <b class="option">-I</b> which allows
the user to supply a single additional include path to use during the
build phase of the package.</p>
<p>Simply use</p>
<pre class="doctools_example">
    critcl -I /path/to/header ...
</pre>
<p>and the specified header will be handed to the package to be built.</p>
</div>
<div id="subsection30" class="doctools_subsection"><h3><a name="subsection30">Introspection of Targets And Configurations</a></h3>
<p>To see a list containing the names of all the available
configurations, run</p>
<pre class="doctools_example">
    critcl -targets
</pre>
<p>The configuration settings for either the default or user-chosen
target can be inspected on <b class="const">stdout</b> with</p>
<pre class="doctools_example">
    critcl -show
</pre>
<p>and</p>
<pre class="doctools_example">
    critcl -show -target TARGET
</pre>
<p>The raw contents of the configuration file used by <b class="cmd"><a href="critcl_pkg.html">critcl</a></b>
are dumped to <b class="const">stdout</b> with</p>
<pre class="doctools_example">
    critcl -showall
</pre>
<p>All of the above can of course be combined with custom configuration
files.</p>
</div>
</div>
<div id="section5" class="doctools_section"><h2><a name="section5">Authors</a></h2>
<p>Jean Claude Wippler, Steve Landers, Andreas Kupries</p>
</div>
<div id="section6" class="doctools_section"><h2><a name="section6">Bugs, Ideas, Feedback</a></h2>
<p>This document, and the package it describes, will undoubtedly contain
bugs and other problems.
Please report them at <a href="https://github.com/andreas-kupries/critcl/issues">https://github.com/andreas-kupries/critcl/issues</a>.
Ideas for enhancements you may have for either package, application,
and/or the documentation are also very welcome and should be reported
at <a href="https://github.com/andreas-kupries/critcl/issues">https://github.com/andreas-kupries/critcl/issues</a> as well.</p>
</div>
<div id="keywords" class="doctools_section"><h2><a name="keywords">Keywords</a></h2>
<p><a href="../index.html#key8">C code</a>, <a href="../index.html#key3">Embedded C Code</a>, <a href="../index.html#key6">code generator</a>, <a href="../index.html#key0">compile &amp; run</a>, <a href="../index.html#key10">compiler</a>, <a href="../index.html#key1">dynamic code generation</a>, <a href="../index.html#key2">dynamic compilation</a>, <a href="../index.html#key9">generate package</a>, <a href="../index.html#key4">linker</a>, <a href="../index.html#key5">on demand compilation</a>, <a href="../index.html#key7">on-the-fly compilation</a></p>
</div>
<div id="category" class="doctools_section"><h2><a name="category">Category</a></h2>
<p>Glueing/Embedded C code</p>
</div>
<div id="copyright" class="doctools_section"><h2><a name="copyright">Copyright</a></h2>
<p>Copyright &copy; Jean-Claude Wippler<br>
Copyright &copy; Steve Landers<br>
Copyright &copy; 2011-2018 Andreas Kupries</p>
</div>
</div></body></html>
